# To change this template, choose Tools | Templates
# and open the template in the editor.

__author__="yangqibin"
__date__ ="$Nov 16, 2011 11:47:50 PM$"
import web
import res_code
import models
import httplib
import json

t_globals = { 'datestr':web.datestr }

render = web.template.render('templates', globals=t_globals)

class SearchApp:
    form = web.form.Form(
      web.form.Textbox('app_name', web.form.notnull, description='app_name'),
      web.form.Button('search')
    )

    def GET(self):
        f = self.form()
        return render.search_app(f, {})

    def POST(self):
        form = self.form()
        if not form.validates():
            return render.search_app(form, {})

        conn = httplib.HTTPConnection('itunes.apple.com')
        conn.request('GET', '/search?limit=10&entity=software&term=' + form.d.app_name)
        res = conn.getresponse()
        data = res.read()
        jd_data = json.loads(data)
#        return jd_data['results'][0]['trackName']
        return render.search_app(form, jd_data['results'])

if __name__ == "__main__":
    print "Hello World"
